/*
 * PatternMatcher.java
 *
 * Created on 27 de abril de 2006, 23:56
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package pattern;

import org.apache.regexp.RE;

import org.apache.log4j.Logger;

/**
 *
 * @author Rincew
 */
public class PatternMatcher 
    implements IPatternMatcher
{
    
    /** Creates a new instance of PatternMatcher */
    public PatternMatcher () {
    }

    /** **/
    public String[] match (String text, IPatternReader patternReaderClass) {
        java.util.ArrayList info = null;
        String p = "";
        RE re = new RE();
        java.util.Iterator patternReader = patternReaderClass.iterator();
        
        while (patternReader.hasNext ()) {
            p = (String) patternReader.next ();
            re = new RE(p);
            if (re.match (text) == true) {
                info = getInfo(re);
                log.debug ("Match found for '"+text 
                + "' with pattern '" + p+"' and info: " + info);
                break;
            } else {
                log.debug ("No match found for '"+text 
                + "' with pattern '" + p+"'");
            }
        }
        
        if (info == null) {
            //log.warn ("Returning an empty match from text '" + text + "'");
            return null;
        }
       
        /*if (info.size ()==0) {
            
        }*/
        String[] a = new String[info.size ()];
        int i;
        for (i = 0; i < info.size (); i++)
            a[i] = (String) info.get (i);
        
        return a;
    }
    
    //--- Helpper method -------------------------------------------
    
    /** Extract all parents from a matching RE
     **/
    private java.util.ArrayList getInfo(RE re) {
        java.util.ArrayList info = new java.util.ArrayList();
        String s;
        int i;
        int nullNumber = 2;
        int nullCount = 0;
        
        for (i = 1; i < 1000; i++) {
            s = re.getParen (i);
            if (s == null) {
                if ( (nullCount++) > nullNumber)
                    break;
            } else
                info.add (s);
        }
        
        return info;
    }

    
     //--- Log ------------------------------------------------------------
    static Logger log;
    static {
        log = Logger.getLogger (PatternMatcher.class.getName());
    }

}
